<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>级联选择</title>
  <script>
    // 模拟年级数据
    var grades = [
      { id:1001, name:'一年级' },
      { id:1002, name:'二年级' },
      { id:1003, name:'三年级' },
    ]
    // 模拟班级数据
    var clazzs = [
      { id:101, name: '一年级1班', gradeId: 1001 },
      { id:102, name: '一年级2班', gradeId: 1001 },
      { id:103, name: '二年级1班', gradeId: 1002 },
      { id:104, name: '二年级2班', gradeId: 1002 },
      { id:105, name: '三年级1班', gradeId: 1003 },
      { id:106, name: '三年级2班', gradeId: 1003 },
    ]
    window.onload = function() {
      // 1.获取目标dom节点
      var grade = document.getElementById('grade');
      var clazz = document.getElementById('clazz');
      // 2.将模拟年级数据遍历，并追加到年级下拉框中
      var mOption = '<option value="">请选择</option>'
      grades.forEach(function(item) {
        mOption += '<option value="'+item.id+'">'+item.name+'</option>'
        grade.innerHTML = mOption
      })
      // 3.当年级下拉框发生改变时
      grade.onchange = function() {
        var value = this.value
        // 当年级选定时，将班级下拉框的禁用放开
        if(value){
          clazz.disabled = false
        } else {
          clazz.disabled = true
          // 年级下拉框变为请选择的时候，将班级下拉框重置为请选择
          clazz.innerHTML = '<option value="">请选择</option>'
        }
        // 遍历班级数据，将符合条件的数据过滤出来
        // mOption是未选择时的默认选项
        var mOption = '<option value="">请选择</option>'
        clazzs.forEach(function(item) {
          // 判断当前班级的gradeId是否和年级选择ID一致
          if(item.gradeId == value){
            mOption += '<option value="'+item.id+'">'+item.name+'</option>'
            clazz.innerHTML = mOption
          }
        })
      }
    }
  </script>
</head>
<body>
  <h3>级联选择器</h3>
  <!-- 年级 -->
  年级：<select name="" id="grade">
    <option value="">请选择</option>
  </select>
  <!-- 班级 -->
  班级：<select name="" id="clazz" disabled>
    <option value="">请选择</option>
  </select>
</body>
</html>